<template>
  <div class="app-container">
    <el-row>
      <el-col :span="5" class="card-box">
        <el-card>
          <div slot="header">
            <el-tag size="small">业务对象分类</el-tag>
            <el-button type="text" icon="el-icon-circle-close" @click="close()" style="float: right; padding: 8px; color: red">退出</el-button>
          </div>
          <div class="hi-full" style="height: 700px">
            <el-tree :data="dataTree" node-key="id" default-expand-all :expand-on-click-node="false">
              <span class="custom-tree-node" slot-scope="{ node, data }" style="width: 100%" @mouseenter="mouseenter(data)" @mouseleave="mouseleave(data)" @click="refresh">
                <span>{{ node.label }}</span>
                <span>
                  <el-button slot="reference" v-show="data.show" type="text" size="mini" icon="el-icon-plus"> </el-button>
                  <el-button slot="reference" v-show="data.show" type="text" size="mini" icon="el-icon-edit-outline"> </el-button>
                  <el-button slot="reference" v-show="data.show" type="text" size="mini" icon="el-icon-minus"> </el-button>
                </span>
              </span>
            </el-tree>
          </div>
        </el-card>
      </el-col>
      <el-col :span="19" class="card-box">
        <el-card style="height: 783px">
          <el-tabs v-model="activeName">
            <el-tab-pane label="基本信息" name="basic">
              <basic-info-form ref="basicInfo" :info="info" />
            </el-tab-pane>
            <el-tab-pane label="字段信息" name="columnInfo">
              <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button type="primary" plain icon="el-icon-plus" size="mini" v-hasPermi="['power:dept:add']" @click="addTableInfo">新增</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button type="success" plain icon="el-icon-edit" size="mini" @click="editTableInfo">编辑</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="deleteTableInfo">删除</el-button>
                </el-col>
              </el-row>

              <el-table ref="dragTable" max-height="600" :data="columns" v-loading="loading" row-key="columnId" border :header-cell-style="{ background: '#eef1f6', color: '#606266' }" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="40" />
                <el-table-column label="名称" prop="columnComment" :show-overflow-tooltip="true" width="220" />
                <el-table-column label="字段" prop="columnName" width="180" />
                <el-table-column label="属性类型" prop="columnType" :show-overflow-tooltip="true" width="220" />
                <el-table-column label="长度" prop="len" width="220" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button type="text" size="small" icon="el-icon-edit" @click="editTableInfo(scope.row)" v-hasPermi="['data:business:edit']">编辑</el-button>
                    <el-button type="text" size="small" icon="el-icon-delete" @click="deleteTableInfo(scope.row)" v-hasPermi="['data:business:remove']">删除</el-button>
                    <el-button type="text" size="small" icon="el-icon-document" @click="details(scope.row)" v-hasPermi="['data:business:details']">明细</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
      <router-view />
    </el-row>
    <el-dialog title="添加表字段" :visible.sync="addTableInfoStatus">
      <el-form :model="tableInfoOne" :rules="rules" :disabled="disable">
        <el-form-item label="名称" prop="columnComment" :label-width="'100px'">
          <el-input v-model="tableInfoOne.columnComment" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="字段名" prop="columnName" :label-width="'100px'">
          <el-input v-model="tableInfoOne.columnName" autocomplete="off"></el-input>
        </el-form-item>

        <el-col :span="12">
          <el-form-item label="类型" prop="columnType" :label-width="'100px'">
            <el-select v-model="tableInfoOne.columnType" placeholder="请选择类型">
              <el-option label="字符串" value="varchar"></el-option>
              <el-option label="大数字" value="bigint"></el-option>
              <el-option label="数字" value="int"></el-option>
              <el-option label="日期" value="datetime"></el-option>
              <el-option label="大文本" value="text"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="长度" prop="len" :label-width="'100px'">
            <el-input-number v-model="tableInfoOne.len" controls-position="right" :min="0" :max="2000"></el-input-number>
          </el-form-item>
        </el-col>
      </el-form>

      <div slot="footer" class="dialog-footer" style="margin-left: -80px; margin-top: 70px" v-if="tableInfoOne.operation == 'add'">
        <el-button @click="addTableInfoStatus = false">取 消</el-button>
        <el-button type="primary" @click="submitFromInfoOne('add')">确 定</el-button>
      </div>
      <div slot="footer" class="dialog-footer" style="margin-left: -80px; margin-top: 70px" v-if="tableInfoOne.operation == 'change'">
        <el-button @click="addTableInfoStatus = false">取 消</el-button>
        <el-button type="primary" @click="submitFromInfoOne('change')">确 定</el-button>
      </div>
      <div slot="footer" class="dialog-footer" style="margin-left: -80px; margin-top: 70px" v-if="tableInfoOne.operation == 'details'"></div>
    </el-dialog>
  </div>
</template>
<script>
import { getGenTable, addFromInfo, updateFromInfo, deleteFromInfo, deleteFromInfoNo, updateFromInfoNo, addFromInfoNo } from '@/api/business/tableInfo'
import basicInfoForm from './basicInfoForm.vue'

import Sortable from 'sortablejs'
import IconsDialog from '../../tool/build/IconsDialog.vue'

export default {
  name: 'TableInfo',

  components: {
    basicInfoForm,
    IconsDialog
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      //树形菜单数据
      dataTree: [
        {
          id: 1,
          label: '业务对象分类表',
          show: false,
          children: []
        }
      ],
      //修改的Id
      updateId: 0,
      // 显示搜索条件
      disable: false,
      // 选中选项卡的 name
      activeName: 'basic',
      // 选中数组
      ids: [],
      // 表信息
      tables: [],
      // 表列信息
      columns: [],
      // 字典信息
      dictOptions: [],
      // 菜单信息
      menus: [],
      // 表详细信息
      info: {},
      //当前的表ID
      tableId: 0,
      //操作标识
      operation: '',
      generate: '',
      //默认弹出框状态
      addTableInfoStatus: false,
      tableInfo: [],
      tableInfoOne: {
        columnId: 0,
        tableId: 0,
        operation: '',
        tableName: '',
        columnComment: '',
        columnName: '',
        columnType: '',
        oldColumnName: '',
        len: 0
      },

      rules: {
        columnComment: [{ required: true, message: '请选择名称', trigger: 'blur' }],
        columnName: [
          { required: true, message: '请输入表字段', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        columnType: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        len: [{ required: true, message: '请输入长度', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.tableId = this.$route.query && this.$route.query.tableId
    this.operation = this.$route.query && this.$route.query.operation
    this.generate = this.$route.query && this.$route.query.generate
    if (this.tableId) {
      // 获取表详细信息
      getGenTable(this.tableId).then((res) => {
        this.loading = true
        this.columns = res.data.rows
        this.info = res.data.info
        this.dataTree[0].children.push({ id: res.data.info.tableId, label: res.data.info.functionName, show: false, children: [] })
        if (res.data.info.subTable) {
          this.dataTree[0].children[0].children.push({ id: res.data.info.subTable.tableId, label: res.data.info.subTable.functionName, show: false, children: [] })
        }

        this.tables = res.data.tables
        this.loading = false
      })
    }
  },
  methods: {
    //删除数据

    deleteTableInfo(row) {
      const $this = this
      this.$modal
        .confirm('是否确认删除表字段名为？')
        .then(function () {
          if (!row.columnName) {
            $this.tableInfo.forEach((element) => {
              element.tableName = $this.info.tableName
              element.operation = 'DROP'
              if ($this.generate == '是') {
                deleteFromInfo(element).then((res) => {})
              } else {
                deleteFromInfoNo(element).then((res) => {})
              }
            })
          } else {
            $this.tableInfoOne.columnId = row.columnId
            $this.tableInfoOne.columnName = row.columnName
            $this.tableInfoOne.tableName = $this.info.tableName
            $this.tableInfoOne.operation = 'DROP'
            if ($this.generate == '是') {
              deleteFromInfo($this.tableInfoOne).then((res) => {})
            } else {
              deleteFromInfoNo($this.tableInfoOne).then((res) => {})
            }
          }
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    //明细
    details(row) {
      this.tableInfoOne.operation = 'details'
      this.disable = true

      this.tableInfoOne.columnId = row.columnId
      this.tableInfoOne.columnComment = row.columnComment
      this.tableInfoOne.columnName = row.columnName
      this.tableInfoOne.oldColumnName = row.oldColumnName
      this.tableInfoOne.columnType = row.columnType
      this.tableInfoOne.len = row.len
      this.addTableInfoStatus = true
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.tableInfo = []
      selection.map((item) =>
        this.tableInfo.push({
          len: item.len,
          columnType: item.columnType,
          columnName: item.columnName,
          columnComment: item.columnComment,
          oldColumnName: item.columnName,
          columnId: item.columnId
        })
      )
    },

    //修改操作
    editTableInfo(row) {
      if (!row.columnName) {
        this.tableInfoOne.columnId = this.tableInfo[0].columnId
        this.tableInfoOne.columnComment = this.tableInfo[0].columnComment
        this.tableInfoOne.columnName = this.tableInfo[0].columnName
        this.tableInfoOne.oldColumnName = this.tableInfo[0].oldColumnName
        this.tableInfoOne.columnType = this.tableInfo[0].columnType
        this.tableInfoOne.len = this.tableInfo[0].len
        this.updateId = row.columnName
      } else {
        this.tableInfoOne.columnId = row.columnId
        this.tableInfoOne.columnComment = row.columnComment
        this.tableInfoOne.columnName = row.columnName
        this.tableInfoOne.oldColumnName = row.oldColumnName
        this.tableInfoOne.columnType = row.columnType
        this.tableInfoOne.len = row.len
        this.updateId = row.columnName
      }

      this.tableInfoOne.operation = 'change'
      this.disable = false
      this.addTableInfoStatus = true
    },

    //提交表字段数据
    submitFromInfoOne(op) {
      if (op == 'add') {
        this.tableInfoOne.tableName = this.info.tableName
        this.tableInfoOne.tableId = this.info.tableId
        if (this.generate == '是') {
          addFromInfo(this.tableInfoOne).then((res) => {
            this.getList()
            this.tableInfoOne = {
              columnId: 0,
              tableId: 0,
              operation: '',
              tableName: '',
              columnComment: '',
              columnName: '',
              columnType: '',
              oldColumnName: '',
              len: 0
            }
            if (res.code == 200) {
              this.$modal.msgSuccess('新增成功')
            }
          })
        } else {
          addFromInfoNo(this.tableInfoOne).then((res) => {
            this.getList()
            this.tableInfoOne = {
              columnId: 0,
              tableId: 0,
              operation: '',
              tableName: '',
              columnComment: '',
              columnName: '',
              columnType: '',
              oldColumnName: '',
              len: 0
            }
            if (res.code == 200) {
              this.$modal.msgSuccess('新增成功')
            }
          })
        }
      } else if (op == 'change') {
        this.tableInfoOne.tableName = this.info.tableName
        this.tableInfoOne.tableId = this.info.tableId
        this.tableInfoOne.oldColumnName = this.updateId

        if (this.generate == '是') {
          updateFromInfo(this.tableInfoOne).then((res) => {
            this.getList()
            this.tableInfoOne = {
              columnId: 0,
              tableId: 0,
              operation: '',
              tableName: '',
              columnComment: '',
              columnName: '',
              columnType: '',
              oldColumnName: '',
              len: 0
            }
            if (res.code == 200) {
              this.$modal.msgSuccess('修改成功')
            }
          })
        } else {
          updateFromInfoNo(this.tableInfoOne).then((res) => {
            this.getList()
            this.tableInfoOne = {
              columnId: 0,
              tableId: 0,
              operation: '',
              tableName: '',
              columnComment: '',
              columnName: '',
              columnType: '',
              oldColumnName: '',
              len: 0
            }
            if (res.code == 200) {
              this.$modal.msgSuccess('修改成功')
            }
          })
        }
      }

      this.addTableInfoStatus = false
    },
    //添加数据库表的字段
    addTableInfo() {
      if (this.operation == 'alter') {
        this.tableInfoOne.operation = 'add'
        this.disable = false
        this.addTableInfoStatus = true
      }
    },

    //页面刷新
    refresh() {
      this.activeName = 'basic'
    },

    mouseleave(data) {
      data.show = false
    },

    mouseenter(data) {
      data.show = true
    },
    getList() {
      getGenTable(this.tableId).then((res) => {
        this.columns = res.data.rows
        this.info = res.data.info
        this.tables = res.data.tables
      })
    },

    getFormPromise(form) {
      return new Promise((resolve) => {
        form.validate((res) => {
          resolve(res)
        })
      })
    },
    /** 关闭按钮 */
    close() {
      const obj = { path: '/data/business', query: { t: Date.now(), pageNum: this.$route.query.pageNum } }
      this.$tab.closeOpenPage(obj)
    }
  },
  mounted() {
    const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
    const sortable = Sortable.create(el, {
      handle: '.allowDrag',
      onEnd: (evt) => {
        const targetRow = this.columns.splice(evt.oldIndex, 1)[0]
        this.columns.splice(evt.newIndex, 0, targetRow)
        for (let index in this.columns) {
          this.columns[index].sort = parseInt(index)
        }
      }
    })
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  min-width: 200px;
  margin-right: 10px;
}
.card-box {
  padding: 0px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.hi-op {
  margin: 10px;
  align-items: center;
  justify-content: space-between;
}
</style>
